package com.kk.xhr.web.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

/**
 * json工具类
 *
 * @author luokexiong
 * @version 1.0 2021/3/6
 * @since 1.0.0
 */
public class JsonUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
    /** 矮驼峰命名mapper */
    private static final ObjectMapper LOWER_CAMEL_CASE_MAPPER;

    static {
        LOWER_CAMEL_CASE_MAPPER = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCaseStrategy.LOWER_CAMEL_CASE);
    }

    /**
     * 支持jsr310 types的object mapper
     * 解决localDateTime解析问题
     *
     * @return json解析对象
     */
    public static ObjectMapper jsr310ObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new SimpleModule().addSerializer(
                new LocalDateTimeSerializer(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
        ).addDeserializer(
                LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
        ));
        return objectMapper;
    }

    public static <T> Optional<String> lowerCamelCaseSerialize(T object) {
        if (null == object) {
            return Optional.empty();
        }
        try {
            return Optional.of(LOWER_CAMEL_CASE_MAPPER.writeValueAsString(object));
        } catch (JsonProcessingException e) {
            LOGGER.error("Serialize to json occurs exception", e);
        }
        return Optional.empty();
    }
}
